<template>
  <view class="wallet-container">
    <!-- 钱包余额 -->
    <view class="wallet-header">
      <view class="balance-section">
        <view class="balance-title">钱包余额</view>
        <view class="balance-amount">
          <text class="amount-symbol">¥</text>
          <text class="amount-value">{{ userInfo.balance || '0.00' }}</text>
        </view>
        <view class="balance-actions">
          <u-button type="primary" size="mini" @click="goRecharge">充值</u-button>
          <u-button type="warning" size="mini" @click="goWithdraw">提现</u-button>
        </view>
      </view>
    </view>
    
    <!-- 交易记录 -->
    <view class="transaction-section">
      <view class="section-header">
        <view class="section-title">交易记录</view>
        <u-tabs :list="tabList" :current="current" @change="handleTabChange"></u-tabs>
      </view>
      
      <view class="transaction-list" v-if="transactionList.length > 0">
        <view class="transaction-item" v-for="(item, index) in transactionList" :key="index">
          <view class="item-left">
            <view class="trans-title">{{ item.title }}</view>
            <view class="trans-time">{{ item.createtime }}</view>
          </view>
          <view class="item-right">
            <view class="trans-amount" :class="{'income': item.type === 'income', 'expense': item.type === 'expense'}">
              {{ item.type === 'income' ? '+' : '-' }}{{ item.amount }}
            </view>
            <view class="trans-status" :class="getStatusClass(item.status)">{{ getStatusText(item.status) }}</view>
          </view>
        </view>
      </view>
      
      <u-empty v-else text="暂无交易记录" mode="list"></u-empty>
      
      <u-loadmore :status="loadStatus" />
    </view>
    
    <!-- 充值弹窗 -->
    <u-popup v-model="showRechargePopup" mode="bottom">
      <view class="popup-container">
        <view class="popup-header">
          <view class="popup-title">余额充值</view>
          <view class="popup-close" @click="showRechargePopup = false">
            <u-icon name="close" size="30"></u-icon>
          </view>
        </view>
        <view class="popup-body">
          <view class="amount-input">
            <view class="input-label">充值金额</view>
            <view class="input-wrapper">
              <text class="input-prefix">¥</text>
              <u-input v-model="rechargeAmount" type="number" placeholder="请输入充值金额" border="none"></u-input>
            </view>
          </view>
          
          <view class="amount-options">
            <view 
              class="amount-option" 
              v-for="(amount, index) in rechargeOptions" 
              :key="index"
              :class="{'active': rechargeAmount == amount}"
              @click="selectRechargeAmount(amount)"
            >
              {{ amount }}元
            </view>
          </view>
          
          <view class="payment-methods">
            <view class="method-title">支付方式</view>
            <view class="methods-list">
              <view 
                class="method-item" 
                v-for="(item, index) in paymentMethods" 
                :key="index"
                :class="{'active': selectedPayment === index}"
                @click="selectPayment(index)"
              >
                <view class="method-icon">
                  <u-icon :name="item.icon" size="40" :color="item.color"></u-icon>
                </view>
                <view class="method-name">{{ item.name }}</view>
                <view class="method-check">
                  <u-icon name="checkmark-circle" size="40" color="#3c9cff" v-if="selectedPayment === index"></u-icon>
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="popup-footer">
          <u-button type="primary" @click="confirmRecharge">确认充值</u-button>
        </view>
      </view>
    </u-popup>
    
    <!-- 提现弹窗 -->
    <u-popup v-model="showWithdrawPopup" mode="bottom">
      <view class="popup-container">
        <view class="popup-header">
          <view class="popup-title">余额提现</view>
          <view class="popup-close" @click="showWithdrawPopup = false">
            <u-icon name="close" size="30"></u-icon>
          </view>
        </view>
        <view class="popup-body">
          <view class="amount-input">
            <view class="input-label">提现金额</view>
            <view class="input-wrapper">
              <text class="input-prefix">¥</text>
              <u-input v-model="withdrawAmount" type="number" placeholder="请输入提现金额" border="none"></u-input>
            </view>
            <view class="balance-info">可提现余额：¥{{ userInfo.balance || '0.00' }}</view>
          </view>
          
          <view class="withdraw-account">
            <view class="account-title">提现账户</view>
            <view class="account-list">
              <view 
                class="account-item" 
                v-for="(item, index) in withdrawAccounts" 
                :key="index"
                :class="{'active': selectedAccount === index}"
                @click="selectAccount(index)"
              >
                <view class="account-icon">
                  <u-icon :name="item.icon" size="40" :color="item.color"></u-icon>
                </view>
                <view class="account-info">
                  <view class="account-name">{{ item.name }}</view>
                  <view class="account-number">{{ item.account }}</view>
                </view>
                <view class="account-check">
                  <u-icon name="checkmark-circle" size="40" color="#3c9cff" v-if="selectedAccount === index"></u-icon>
                </view>
              </view>
            </view>
            <view class="add-account" @click="addAccount">
              <u-icon name="plus-circle" size="40" color="#3c9cff"></u-icon>
              <text>添加提现账户</text>
            </view>
          </view>
        </view>
        <view class="popup-footer">
          <u-button type="primary" @click="confirmWithdraw">确认提现</u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { user } from '@/api/cms'

export default {
  data() {
    return {
      userInfo: {
        balance: '0.00'
      },
      tabList: [
        { name: '全部' },
        { name: '收入' },
        { name: '支出' },
        { name: '充值' },
        { name: '提现' }
      ],
      current: 0,
      transactionList: [],
      page: 1,
      limit: 10,
      loadStatus: 'loadmore',
      
      // 充值相关
      showRechargePopup: false,
      rechargeAmount: '',
      rechargeOptions: [10, 50, 100, 200, 500, 1000],
      paymentMethods: [
        { name: '微信支付', icon: 'weixin-circle', color: '#09BB07' },
        { name: '支付宝', icon: 'zhifubao-circle', color: '#1677FF' }
      ],
      selectedPayment: 0,
      
      // 提现相关
      showWithdrawPopup: false,
      withdrawAmount: '',
      withdrawAccounts: [
        { name: '微信', account: 'wx_123456', icon: 'weixin-circle', color: '#09BB07' },
        { name: '支付宝', account: 'alipay@example.com', icon: 'zhifubao-circle', color: '#1677FF' }
      ],
      selectedAccount: 0
    }
  },
  onLoad() {
    this.getUserInfo()
    this.getTransactionList()
  },
  onPullDownRefresh() {
    this.page = 1
    this.transactionList = []
    Promise.all([
      this.getUserInfo(),
      this.getTransactionList()
    ]).then(() => {
      uni.stopPullDownRefresh()
    })
  },
  onReachBottom() {
    if (this.loadStatus === 'loadmore') {
      this.page++
      this.getTransactionList()
    }
  },
  methods: {
    // 获取用户信息
    async getUserInfo() {
      try {
        const { data } = await user.getUserInfo()
        if (data.code === 1) {
          this.userInfo = data.data.userInfo
        } else {
          uni.showToast({
            title: data.msg || '获取用户信息失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取用户信息失败', error)
        uni.showToast({
          title: '获取用户信息失败，请稍后再试',
          icon: 'none'
        })
      }
    },
    
    // 获取交易记录
    async getTransactionList() {
      try {
        this.loadStatus = 'loading'
        
        // 根据当前选中的标签页确定类型筛选
        let type = ''
        if (this.current === 1) {
          type = 'income'
        } else if (this.current === 2) {
          type = 'expense'
        } else if (this.current === 3) {
          type = 'recharge'
        } else if (this.current === 4) {
          type = 'withdraw'
        }
        
        const params = {
          page: this.page,
          limit: this.limit,
          type: type
        }
        
        const { data } = await user.getMoneyLog(params)
        
        if (data.code === 1) {
          if (this.page === 1) {
            this.transactionList = data.data.rows
          } else {
            this.transactionList = [...this.transactionList, ...data.data.rows]
          }
          
          this.loadStatus = data.data.rows.length < this.limit ? 'nomore' : 'loadmore'
        } else {
          this.loadStatus = 'loadmore'
          uni.showToast({
            title: data.msg || '获取交易记录失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取交易记录失败', error)
        this.loadStatus = 'loadmore'
        uni.showToast({
          title: '获取交易记录失败，请稍后再试',
          icon: 'none'
        })
      }
    },
    
    // 处理标签页切换
    handleTabChange(index) {
      this.current = index
      this.page = 1
      this.transactionList = []
      this.getTransactionList()
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        success: '成功',
        pending: '处理中',
        failed: '失败'
      }
      return statusMap[status] || '未知'
    },
    
    // 获取状态样式类
    getStatusClass(status) {
      const classMap = {
        success: 'status-success',
        pending: 'status-pending',
        failed: 'status-failed'
      }
      return classMap[status] || ''
    },
    
    // 跳转到充值页面
    goRecharge() {
      this.showRechargePopup = true
    },
    
    // 跳转到提现页面
    goWithdraw() {
      this.showWithdrawPopup = true
    },
    
    // 选择充值金额
    selectRechargeAmount(amount) {
      this.rechargeAmount = amount
    },
    
    // 选择支付方式
    selectPayment(index) {
      this.selectedPayment = index
    },
    
    // 选择提现账户
    selectAccount(index) {
      this.selectedAccount = index
    },
    
    // 添加提现账户
    addAccount() {
      uni.navigateTo({
        url: '/pages_mine/pages/wallet/account'
      })
    },
    
    // 确认充值
    async confirmRecharge() {
      if (!this.rechargeAmount || this.rechargeAmount <= 0) {
        uni.showToast({
          title: '请输入有效的充值金额',
          icon: 'none'
        })
        return
      }
      
      try {
        uni.showLoading({
          title: '处理中'
        })
        
        const params = {
          amount: this.rechargeAmount,
          payment_type: this.selectedPayment
        }
        
        const { data } = await user.recharge(params)
        
        uni.hideLoading()
        
        if (data.code === 1) {
          // 根据支付方式调用不同的支付接口
          if (this.selectedPayment === 0) {
            // 微信支付
            this.wxPay(data.data)
          } else if (this.selectedPayment === 1) {
            // 支付宝支付
            this.aliPay(data.data)
          }
        } else {
          uni.showToast({
            title: data.msg || '充值失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        console.error('充值失败', error)
        uni.showToast({
          title: '充值失败，请稍后再试',
          icon: 'none'
        })
      }
    },
    
    // 确认提现
    async confirmWithdraw() {
      if (!this.withdrawAmount || this.withdrawAmount <= 0) {
        uni.showToast({
          title: '请输入有效的提现金额',
          icon: 'none'
        })
        return
      }
      
      if (parseFloat(this.withdrawAmount) > parseFloat(this.userInfo.balance)) {
        uni.showToast({
          title: '提现金额不能大于可用余额',
          icon: 'none'
        })
        return
      }
      
      try {
        uni.showLoading({
          title: '处理中'
        })
        
        const params = {
          amount: this.withdrawAmount,
          account_id: this.selectedAccount
        }
        
        const { data } = await user.withdraw(params)
        
        uni.hideLoading()
        
        if (data.code === 1) {
          uni.showToast({
            title: '提现申请已提交',
            icon: 'success'
          })
          
          // 关闭弹窗
          this.showWithdrawPopup = false
          
          // 刷新数据
          this.getUserInfo()
          this.page = 1
          this.transactionList = []
          this.getTransactionList()
        } else {
          uni.showToast({
            title: data.msg || '提现失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        console.error('提现失败', error)
        uni.showToast({
          title: '提现失败，请稍后再试',
          icon: 'none'
        })
      }
    },
    
    // 微信支付
    wxPay(orderInfo) {
      // 模拟支付成功
      setTimeout(() => {
        this.paySuccess()
      }, 1000)
    },
    
    // 支付宝支付
    aliPay(orderInfo) {
      // 模拟支付成功
      setTimeout(() => {
        this.paySuccess()
      }, 1000)
    },
    
    // 支付成功
    paySuccess() {
      uni.showToast({
        title: '充值成功',
        icon: 'success'
      })
      
      // 关闭弹窗
      this.showRechargePopup = false
      
      // 刷新数据
      this.getUserInfo()
      this.page = 1
      this.transactionList = []
      this.getTransactionList()
    }
  }
}
</script>

<style lang="scss" scoped>
.wallet-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.wallet-header {
  background: linear-gradient(135deg, #3c9cff, #5c6bc0);
  padding: 40rpx 30rpx;
  color: #ffffff;
}

.balance-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  
  .balance-title {
    font-size: 28rpx;
    margin-bottom: 10rpx;
  }
  
  .balance-amount {
    margin-bottom: 30rpx;
    
    .amount-symbol {
      font-size: 36rpx;
      vertical-align: top;
    }
    
    .amount-value {
      font-size: 60rpx;
      font-weight: bold;
    }
  }
  
  .balance-actions {
    display: flex;
    
    .u-button {
      margin: 0 20rpx;
      min-width: 160rpx;
    }
  }
}

.transaction-section {
  background-color: #ffffff;
  margin-top: 20rpx;
  padding-bottom: 30rpx;
}

.section-header {
  padding: 20rpx 30rpx 0;
  
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333333;
    margin-bottom: 20rpx;
  }
}

.transaction-list {
  padding: 0 30rpx;
}

.transaction-item {
  display: flex;
  justify-content: space-between;
  padding: 30rpx 0;
  border-bottom: 1px solid #f5f5f5;
  
  &:last-child {
    border-bottom: none;
  }
  
  .item-left {
    flex: 1;
    
    .trans-title {
      font-size: 28rpx;
      color: #333333;
      margin-bottom: 10rpx;
    }
    
    .trans-time {
      font-size: 24rpx;
      color: #999999;
    }
  }
  
  .item-right {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    
    .trans-amount {
      font-size: 32rpx;
      font-weight: bold;
      margin-bottom: 10rpx;
      
      &.income {
        color: #5ac725;
      }
      
      &.expense {
        color: #f56c6c;
      }
    }
    
    .trans-status {
      font-size: 24rpx;
      
      &.status-success {
        color: #5ac725;
      }
      
      &.status-pending {
        color: #f9ae3d;
      }
      
      &.status-failed {
        color: #f56c6c;
      }
    }
  }
}

.popup-container {
  background-color: #ffffff;
  border-top-left-radius: 16rpx;
  border-top-right-radius: 16rpx;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1px solid #f5f5f5;
  
  .popup-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333333;
  }
}

.popup-body {
  padding: 30rpx;
}

.amount-input {
  margin-bottom: 30rpx;
  
  .input-label {
    font-size: 28rpx;
    color: #333333;
    margin-bottom: 20rpx;
  }
  
  .input-wrapper {
    display: flex;
    align-items: center;
    border-bottom: 1px solid #e5e5e5;
    padding-bottom: 10rpx;
    
    .input-prefix {
      font-size: 40rpx;
      font-weight: bold;
      color: #333333;
      margin-right: 10rpx;
    }
  }
  
  .balance-info {
    font-size: 24rpx;
    color: #999999;
    margin-top: 10rpx;
  }
}

.amount-options {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 30rpx;
  
  .amount-option {
    width: calc(33.33% - 20rpx);
    height: 80rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    border: 1px solid #e5e5e5;
    border-radius: 8rpx;
    margin: 10rpx;
    font-size: 28rpx;
    color: #333333;
    
    &.active {
      border-color: #3c9cff;
      color: #3c9cff;
      background-color: rgba(60, 156, 255, 0.1);
    }
  }
}

.payment-methods, .withdraw-account {
  margin-bottom: 30rpx;
  
  .method-title, .account-title {
    font-size: 28rpx;
    color: #333333;
    margin-bottom: 20rpx;
  }
  
  .methods-list, .account-list {
    border: 1px solid #e5e5e5;
    border-radius: 8rpx;
    overflow: hidden;
  }
  
  .method-item, .account-item {
    display: flex;
    align-items: center;
    padding: 20rpx;
    border-bottom: 1px solid #f5f5f5;
    
    &:last-child {
      border-bottom: none;
    }
    
    &.active {
      background-color: #f9f9f9;
    }
    
    .method-icon, .account-icon {
      margin-right: 20rpx;
    }
    
    .method-name, .account-info {
      flex: 1;
      
      .account-name {
        font-size: 28rpx;
        color: #333333;
      }
      
      .account-number {
        font-size: 24rpx;
        color: #999999;
      }
    }
  }
  
  .add-account {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20rpx 0;
    margin-top: 20rpx;
    
    text {
      font-size: 28rpx;
      color: #3c9cff;
      margin-left: 10rpx;
    }
  }
}

.popup-footer {
  padding: 0 30rpx 30rpx;
}
</style>